package com.xianbeiying.app.ckgl.activity;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.util.LogUtils;
import com.xianbeiying.app.ckgl.MyApplication;
import com.xianbeiying.app.ckgl.R;
import com.xianbeiying.app.ckgl.bean.UpdateBean;
import com.xianbeiying.app.ckgl.bean.UrlBean;
import com.xianbeiying.app.ckgl.downfile.NotificationUpdateActivity;
import com.xianbeiying.app.ckgl.fragment.CounselFragment;
import com.xianbeiying.app.ckgl.fragment.HomeFragment;
import com.xianbeiying.app.ckgl.fragment.MyFragment;
import com.xianbeiying.app.ckgl.fragment.NoticeFragment;
import com.xianbeiying.app.ckgl.http.HttpCallBackUtil;
import com.xianbeiying.app.ckgl.model.UpdateModel;
import com.xianbeiying.app.ckgl.util.SharedPreferencesUtils;
import com.xianbeiying.app.ckgl.util.Tools;
import com.xianbeiying.app.ckgl.widght.popwindow.CenterPopWindow;

/**
 * 主界面
 */
public class MainActivity extends BaseActivity implements HttpCallBackUtil, View.OnClickListener {
    RadioGroup rd_rb;
    RadioButton rb_home, rb_zhixun, rb_gonggao, rb_me;
    public static int fragmentid = 0;
    private UpdateModel updateModel;
    private MyApplication app;// 应用对象
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        app = (MyApplication) getApplication();
        updateModel = new UpdateModel(this);
        updateModel.addResponseListener(this);
        isPermisson = true;
        if (!SharedPreferencesUtils.getBooleanDate("isShow")) {
            startActivity(new Intent().setClass(MainActivity.this, WelcomeActivity.class));
            finish();
        } else {
            setContentView(R.layout.activity_main);
            initView();
        }
    }

    private void initView() {
        rd_rb = (RadioGroup) findViewById(R.id.rd_rb);
        rb_home = (RadioButton) findViewById(R.id.rb_home);
        rb_zhixun = (RadioButton) findViewById(R.id.rb_zhixun);
        rb_gonggao = (RadioButton) findViewById(R.id.rb_gonggao);
        rb_me = (RadioButton) findViewById(R.id.rb_me);
        initEvent();
    }
    public static boolean isAddFragment=true;//是否加载fragment
    @Override
    protected void onResume() {
        super.onResume();
        if(isAddFragment){
            setFragment(fragmentid);
        }
        //是否进行下载，下载完成后，不再进行下载
//        if (MyApplication.isDownFile) {
//            if (MyApplication.isShowDown)
//                updateModel.UpdateApk("UPGRADE_VERSION", true);
//        }
    }

    private void initEvent() {
        rd_rb.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_home) {
                    //首页
                    fragmentid = 0;
                    isAddFragment=true;
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.ly_home_layout, HomeFragment.getInstance());
                    transaction.commit();
                } else if (checkedId == R.id.rb_zhixun) {
                    //咨询
                    isAddFragment=true;
                    if (MyApplication.isLogin) {
                    fragmentid = 1;
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.ly_home_layout, CounselFragment.getInstance());
                    transaction.commit();}else{
                        startActivity(new Intent().setClass(MainActivity.this, LoginActivity.class));
                    }
                } else if (checkedId == R.id.rb_zhibei) {
                    //功能操作
                    startActivity(new Intent().setClass(MainActivity.this, FunctionOperateActivity.class));
                } else if (checkedId == R.id.rb_gonggao) {
                    //公告
                    fragmentid = 2;
                    isAddFragment=true;
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.ly_home_layout, NoticeFragment.getInstance());
                    transaction.commit();
                } else if (checkedId == R.id.rb_me) {
                    isAddFragment=true;
                    if (MyApplication.isLogin){
                        //我的
                        fragmentid = 3;
                        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                        transaction.replace(R.id.ly_home_layout, MyFragment.getInstance());
                        transaction.commit();
                    } else {
                        startActivity(new Intent().setClass(MainActivity.this, LoginActivity.class));
                    }
                }
            }
        });
    }

    private void setFragment(int fragmentid) {
        switch (fragmentid) {
            case 0:
                //首页
                rb_home.setChecked(true);
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.ly_home_layout, HomeFragment.getInstance());
                transaction.commit();
                break;
            case 1:
                if(MyApplication.isLogin) {
                rb_zhixun.setChecked(true);
                //咨询
                FragmentTransaction transaction1 = getSupportFragmentManager().beginTransaction();
                transaction1.replace(R.id.ly_home_layout, CounselFragment.getInstance());
                transaction1.commit();}
                else{
                    startActivity(new Intent().setClass(MainActivity.this, LoginActivity.class));
                }
                break;
            case 2:
                rb_gonggao.setChecked(true);
                //公告
                FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction();
                transaction2.replace(R.id.ly_home_layout, NoticeFragment.getInstance());
                transaction2.commit();
                break;
            case 3:
                if (MyApplication.isLogin) {
                    //我的
                    rb_me.setChecked(true);
                    FragmentTransaction transaction3 = getSupportFragmentManager().beginTransaction();
                    transaction3.replace(R.id.ly_home_layout, MyFragment.getInstance());
                    transaction3.commit();
                } else {
                    startActivity(new Intent().setClass(MainActivity.this, LoginActivity.class));
                }
                break;
        }
    }

    private UpdateBean updateBean;

    @Override
    public void onCallBackData(String url, Object content){
        if (url.equals("更新apk")) {
            updateBean = JSON.parseObject(new String((byte[]) content), UpdateBean.class);
            if (updateBean.isR()) {
                LogUtils.e("更新apk---------------");
                getAppVersionsNumber(updateBean.getV().getVERSION().getVersionCode(), "http://" + MyApplication.IP + UrlBean.IMAGES + updateBean.getV().getVERSION().getVersionUrl());
            }
        }
    }

    private int currentVersionCode;// 版本号;
    private int code1, code2, code3;

    // 获取本应用的版本号
    private void getAppVersionsNumber(String newVersion, String downurl) {
        try {
            LogUtils.e("更新apk---------------" + newVersion);
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(
                    this.getPackageName(), 0);
            currentVersionCode = info.versionCode; // 版本号
//            showDailog(downurl);
//            AppChangen.showUpdateDialog(this,
//                    downurl, app);
            if (newVersion.contains(".")) {
                String[] rversincode = newVersion.split("\\.");
                code1 = Integer.valueOf(rversincode[0]);
                code2 = Integer.valueOf(rversincode[1]);
                if (code1 > currentVersionCode) {
                    MyApplication.isShowDown = true;
//                    AppChangen.showUpdateDialog(this,
//                            downurl, app);
                    showDailog(downurl);
                } else if (code1 == currentVersionCode) {
                    if (code2 > currentVersionCode) {
//                        AppChangen.showUpdateDialog(this,
//                                downurl, app);
                        showDailog(downurl);
                    } else {
                        MyApplication.isShowDown = false;
                    }
                } else {
                    MyApplication.isShowDown = false;
                }
            } else {
                code3 = Integer.valueOf(newVersion);
                if (code3 > currentVersionCode) {
                    MyApplication.isShowDown = true;
//                    AppChangen.showUpdateDialog(this,
//                            downurl, app);
                    showDailog(downurl);
                } else {
                    MyApplication.isShowDown = false;
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private CenterPopWindow updateAppView;
    private Button bt1, bt2;//确定和取消按钮
    private ImageView checkBox;
    private boolean isCheck;
    private String versionsUrl;

    private void showDailog(String versionsUrls) {
        this.versionsUrl = versionsUrls;
        isCheck = SharedPreferencesUtils.getBooleanDate("Check");
        updateAppView = new CenterPopWindow(this, R.layout.dialog_normal_layout);
        bt1 = updateAppView.getView(R.id.positiveButton);
        bt2 = updateAppView.getView(R.id.negativeButton);
        checkBox = updateAppView.getView(R.id.checkBox);
        bt1.setOnClickListener(this);
        bt2.setOnClickListener(this);
        checkBox.setOnClickListener(this);
        if (isCheck) {
            checkBox.setSelected(true);
            MyApplication.isShowDown = false;
        } else {
            checkBox.setSelected(false);
            MyApplication.isShowDown = true;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.positiveButton:
                if (Tools.ExistSDCard()) {
                    isAddFragment=false;
                    Intent it = new Intent(this,
                            NotificationUpdateActivity.class);
                    startActivity(it);
                    app.setDownload(true);
                    app.setVersionsUrl(versionsUrl);
                    updateAppView.dismiss();

                } else {
                    Toast.makeText(this, "手机未安装sd卡",
                            Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.negativeButton:
                isAddFragment=true;
                updateAppView.dismiss();
                break;
            case R.id.checkBox:
                if (isCheck) {
                    checkBox.setSelected(false);
                    SharedPreferencesUtils.setBooleanDate("Check", false);
                } else {
                    checkBox.setSelected(true);
                    SharedPreferencesUtils.setBooleanDate("Check", true);
                }
                break;

        }
    }

    //改写物理按键——返回的逻辑
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if(fragmentid==1){
        if(keyCode==KeyEvent.KEYCODE_BACK)
        {
            if(CounselFragment.webView!=null&&CounselFragment.webView.canGoBack())
            {
                CounselFragment.webView.goBack();//返回上一页面
                setFragment(fragmentid);
                return true;
            }
            else
            {
               finish();
            }
        }}
        return super.onKeyDown(keyCode, event);
    }
}
